package org.meichao.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class OkHttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(OkHttpUtils.class);

    public static final OkHttpClient client = new OkHttpClient().newBuilder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS).build();

    /**
     * Post请求
     * @param url
     * @param bodyParam
     * @return
     * @throws IOException
     */
    public static String doPost(String url, Map<String, String> bodyParam) throws IOException {
        logger.info("Post请求,url：{}，入参：{}", url, bodyParam);
        FormBody.Builder formBody = new FormBody.Builder();
        if (bodyParam != null && !bodyParam.isEmpty()) {
            for (Map.Entry<String, String> entry : bodyParam.entrySet()) {
                formBody.add(entry.getKey(), entry.getValue());
            }
        }
        RequestBody body = formBody.build();
        return sendRequest(url, body);
    }

    /**
     * Post请求-Json
     * @return
     */
    public static String doJsonPost(String url, JSONObject jsonObject) throws IOException {
        logger.info("JsonPost请求,url：{}，入参：{}", url, jsonObject);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toJSONString());
        return sendRequest(url, body);
    }

    /**
     * Post发送请求
     * @param url
     * @param body
     * @return
     * @throws IOException
     */
    private static String sendRequest(String url, RequestBody body) throws IOException {
        Request request = new Request.Builder().url(url).post(body).build();
        Response response = client.newCall(request).execute();
        logger.info("response:{}", JSONObject.toJSONString(response));
        if(response.isSuccessful()){
            return response.body().string();
        }
        return "";
    }

    /**
     * get请求
     *
     * @param url
     * @param param
     * @return
     * @throws IOException
     */
    public static String doGet(String url, Map<String, String> param) throws IOException {
        logger.info("JsonPost请求,url：{}，入参：{}", url, param);
        HttpUrl.Builder builder = HttpUrl.parse(url).newBuilder();
        if (param != null && !param.isEmpty()) {
            for (Map.Entry<String, String> entry : param.entrySet()) {
                builder.addQueryParameter(entry.getKey(), entry.getValue());
            }
        }
        Request request = new Request.Builder().url(builder.build()).get().build();
        Response response = client.newCall(request).execute();
        logger.info("response:{}", JSONObject.toJSONString(response));
        if (response.isSuccessful()) {
            return response.body().string();
        }
        return "";
    }

}
